import Vue from 'vue'
import VueRouter from 'vue-router'
import swal from 'sweetalert';

let sessionstorage = require("sessionstorage");

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    // 一般叫做重定向，意思就是默认访问页面的时候就是 / 跳转到 /login 路由
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/admin',
    name: 'Admin-Home',
    /* 知道后台首页默认页面 */
    redirect: '/admin/staff/list',
    component: () => import('@/views/Admin.vue'),
    /* 后台所有的功能都是 /admin 子路由 */
    children: [
      {
        path: 'staff/add',
        name: 'Admin-staff-add',
        component: () => import('@/views/Staff-add.vue')
      },
      {
        path: 'staff/list',
        name: 'Admin-staff-list',
        component: () => import('@/views/Staff-list.vue')
      },
      /* 部门相关路由信息 */
      {
        path: 'depart/add',
        name: 'Admin-depart-add',
        component: () => import('@/views/Depart-add.vue')
      },
      {
        path: 'depart/list',
        name: 'Admin-depart-list',
        component: () => import('@/views/Depart-list.vue')
      },
      /* 工资相关路由信息 */
      {
        path: 'salary/add',
        name: 'Admin-salary-add',
        component: () => import('@/views/Salary-add.vue')
      },
      {
        path: 'salary/list',
        name: 'Admin-salary-list',
        component: () => import('@/views/Salary-list.vue')
      }
    ]
  },
  {
    path: '/admin/logout',
    name: 'Logout',
    redirect: '/login'
  },

]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.redirectedFrom == '/admin/logout') {
    sessionstorage.removeItem('token');
  }
  if (sessionstorage.getItem('token') == null) {
    if (to.path != '/login') {
      swal("未登录!", "请先登录再进行访问!", "error");
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
})

export default router
